package com.icbc.service;

import com.icbc.dao.SpitDao;
import com.icbc.pojo.Spit;
import com.icbc.utils.IdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * 吐槽服务
 */
@Service
public class SpitService {

    @Autowired
    private SpitDao spitDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    //查询全部(不包含评论)
    public List<Spit> findByParentidIsNull(){
        List<Spit> res = spitDao.findByParentidIsNull();
        return res;
    }

    //查询一个
    public Spit findById(String id){
        return spitDao.findById(id).get();
    }

    //新增一个
    public void seve(Spit spit){
        spit.setId(idWorker.nextId()+"");
        spitDao.save(spit);

        //如果是评论，被评论的吐槽评论数加1
        if(StringUtils.isNoneBlank(spit.getParentid())){
            //条件对象
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));

            //变化对象
            Update update = new Update();
            update.inc("comment",1);

            //执行
            mongoTemplate.updateFirst(query, update,"spit");
        }

    }

    //修改一个
    public void update(Spit spit){
       spitDao.save(spit);
    }

    //删除一个

    public void delete(String id){
        spitDao.deleteById(id);
    }

    //根据父id查询评论(翻页查询)
    public Page<Spit> common(String parentid, int page, int size) {
        return spitDao.findByParentid(parentid, PageRequest.of(page-1,size));
    }

    //正常翻页查询(翻页查询)
    public Page<Spit> search( int page, int size,Spit spit) {


        //创建条件对象
        Query query = new Query();

        if(spit.getId()!=null){
            query.addCriteria(Criteria.where("_id").is(spit.getId()));
        }

        Page<Spit> all = spitDao.findAll(PageRequest.of(page - 1, size));


        return all;
    }



    /**
     * 吐槽点赞
     * @param id
     */
    public void thumbup(String id) {

        //条件
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));

        //变化
        Update update = new Update();
        update.inc("thumbup",1);

        //增加点赞数（执行）
        mongoTemplate.updateFirst(query,update,"spit");

    }

}
